﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace X.Common
{
    public class Cryptography
    {
        private const int saltLength = 4;

        public static byte[] CreateDbPassword(byte[] unsaltedPassword)
        {
            byte[] saltValue = new byte[saltLength];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(saltValue);
            return CreateSaltedPassword(saltValue, unsaltedPassword);
        }

        public static bool ComparePasswords(byte[] storedPassword, byte[] hashedPassword)
        {
            if (null == storedPassword || null == hashedPassword || hashedPassword.Length != storedPassword.Length - saltLength)
                return false;
            byte[] saltValue = new byte[saltLength];
            int saltOffset = storedPassword.Length - saltLength;
            for (int i = 0; i < saltLength; i++)
                saltValue[i] = storedPassword[saltOffset + i];
            byte[] saltedPassword = CreateSaltedPassword(saltValue, hashedPassword);
            return CompareByteArray(storedPassword, saltedPassword);
        }

        private static byte[] CreateSaltedPassword(byte[] saltValue, byte[] unsaltedPassword)
        {
            byte[] rawSalted = new byte[unsaltedPassword.Length + saltValue.Length];
            unsaltedPassword.CopyTo(rawSalted, 0);
            saltValue.CopyTo(rawSalted, unsaltedPassword.Length);
            SHA1 sha1 = SHA1.Create();
            byte[] saltedPassword = sha1.ComputeHash(rawSalted);
            byte[] dbPassword = new byte[saltedPassword.Length + saltValue.Length];
            saltedPassword.CopyTo(dbPassword, 0);
            saltValue.CopyTo(dbPassword, saltedPassword.Length);
            return dbPassword;
        }

        private static bool CompareByteArray(byte[] array1, byte[] array2)
        {
            if (array1.Length != array2.Length)
                return false;

            for (int i = 0; i < array1.Length; i++)
            {
                if (array1[i] != array2[i])
                    return false;
            }

            return true;
        }
    }
}
